/**
 * WeeShop 声明
 * ===========================================================
 * 网站： https://www.darlang.com
 * 标题： ECShop 小程序「weeshop 」- 基于 ECShop 为后台系统开发的非官方微信商城小程序
 * 链接： https://www.darlang.com/?p=709
 * 说明： 源码已开源并遵循 Apache 2.0 协议，你有权利进行任何修改，但请保留出处，请不要删除该注释。
 * ==========================================================
 * Copyright 2019 darlang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ===========================================================
 */

/**
 * WeeShop 使用说明
 * ===========================================================
 * 先看根目录的 README.md 文件说明
 * 后修改根目录的 weeshop.config.js
 * ==========================================================
 * 先看根目录的 README.md 文件说明
 * 后修改根目录的 weeshop.config.js
 * ==========================================================
* 先看根目录的 README.md 文件说明
* 后修改根目录的 weeshop.config.js
* ==========================================================
 */


// index.js
import {PNT,setNavBarTitle,showToast,pushPagePath,pointsMall,getUrlParamValue,shopNoticeCatId} from "../../utils/utils";
import { GetSiteInfo, GetBannerList, GetArticleList, GetHomeGoodsList, GetIndex, GetIndexPage, FlashSaleBytime} from '../../utils/apis';
import {CheckCartTotal} from "../../utils/publics";

let goodsList = [
  { actEndTime: '2019/11/30 10:00:43' },
  
]
var inter;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    flag:true,
    countDownList: [],
    actEndTimeList: [],
    index:-1,
    siteInfo: '',
    bannerLst: '',
    mainMenu: [

      {
        type: 'qiangou',
        title: '限时抢购',
        img: 'https://donglongshangshi.com/mobile/public/index_new/images/tb2.png'
      },
      {
        type: 'score',
        title: '积分兑换',
        img: 'https://donglongshangshi.com/mobile/public/index_new/images/tb3.png'
      },
      {
        type: 'coupon',
        title: '领劵中心',
        img: 'https://donglongshangshi.com/mobile/public/index_new/images/tb4.png'
      },
      {
        type: 'sign',
        title: '我要赚钱',
        img: 'https://donglongshangshi.com/mobile/public/index_new/images/tb5.png'
      },
      {
        type: 'activities',
        title: '拼团专区',
        img: 'https://donglongshangshi.com/mobile/public/index_new/images/tb1.png'
      }
    ],
    noticeLst: [],
    goodProducts: [],
    hotProducts: [],
    recentlyProducts: [],
    cat:0,
    page:1,
    flash:[],
    flashFlag:false,
    strtotime:0,
    title:0,
    recommend:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {

    setNavBarTitle(PNT.default);
    this.loginModal = this.selectComponent("#login-modal");

    // this.getShopSiteInfo();
    this.getBanner();
    this.getNotices();
    this.getPorducts();
    this.getIndex();
    this.flashSaleBytime();
    // 倒计时
    let endTimeList = [];
    // 将活动的结束时间参数提成一个单独的数组，方便操作
    goodsList.forEach(o => { endTimeList.push(o.actEndTime) })
    this.setData({ actEndTimeList: endTimeList });
    // 执行倒计时函数
    // this.countDown();
    wx.showLoading({
      title: '数据加载中...',
    })
  },
  timeFormat(param) {//小于10的格式化函数
    return param < 10 ? '0' + param : param;
  },
  countDown() {//倒计时函数
    // 获取当前时间，同时得到活动结束时间数组
    let newTime = new Date().getTime();
    let endTimeList = this.data.strtotime;
    // let countDownArr = [];

    // 对结束时间进行处理渲染到页面
    // endTimeList.forEach(o => {
    // let endTime = new Date(o).getTime();
    let endTime = endTimeList * 1000;
    let obj = null;
    // 如果活动未结束，对时间进行处理
    if (endTime - newTime > 0) {
      let time = (endTime - newTime) / 1000;
      // 获取天、时、分、秒
      // let day = parseInt(time / (60 * 60 * 24));
      let hou = parseInt(time / 3600);
      let min = parseInt(time % 3600 / 60);
      let sec = parseInt(time % 3600 % 60);
      obj = {
        // day: this.timeFormat(day),
        hou: hou,
        min: min,
        sec: sec
      }
    } else {//活动已结束，全部设置为'00'
      obj = {
        hou: '00',
        min: '00',
        sec: '00'
      }
      // wx.showToast({
      //   title: '活动已结束',
      //   icon: 'none',
      // })
      // this.flashSaleBytime();
    }
    // countDownArr.push(obj);
    // })
    // 渲染，然后每隔一秒执行一次倒计时函数
    this.setData({ obj: obj })
    inter = setTimeout(this.countDown, 1000);
  },
  /**
  * 获取首页信息
  * @author darlang
  */
  getIndex() {
    GetIndex().then(res => {
      //console.log(res)
      this.setData({
        cat_goods:res.data,
        goodProducts: res.recommend,
        sort:res.sort,
        recommend:res.recommend,
      })
      //console.log(res.data)
      return;
      this.setData({
        siteInfo: res.data.site_info
      });
      setNavBarTitle(res.data.site_info.name || PNT.default);
    });
  }, 

  /**
  * 获取首页分页信息
  * @author darlang
  */
  getIndexPage(){
    var that = this;
    var page = this.data.page;
    var index = this.data.index;
    var goods = this.data.goodProducts;
    GetIndexPage(page,index).then(res => {

      if(res.data.length>0){

        page = page + 1;

        for(var i = 0;i<res.data.length;i++){

          goods.push(res.data[i]);

        }

        that.setData({
          goodProducts:goods,
          page:page,
        })

      }else{
        wx.showLoading({
          title: '数据已加载完毕',
        })
        setTimeout(function(){
          wx.hideLoading();
        },2000)
      }
      // console.log(res)
      // this.setData({
      //   cat_goods: res.data,
      //   goodProducts: res.data[0].goods,

      // })
      // console.log(res.data)
      return;
      this.setData({
        siteInfo: res.data.site_info
      });
      setNavBarTitle(res.data.site_info.name || PNT.default);
    });
  },

//分类切换  goodProducts
  switchcat:function(e){
    var cat_goods = this.data.cat_goods;
    var items = e.currentTarget.dataset;
    console.log(items)
    if(items.index == -1){
      this.setData({
        goodProducts: this.data.recommend,
        index: items.index,
        cat: -1,
        page: 1,
      })
    }else{
      this.setData({
        goodProducts: cat_goods[items.index].goods,
        index: items.index,
        cat: items.cat,
        page: 1,
      })
    }

  },

  /**
   * 获取站点信息
   * @author darlang
   */
  getShopSiteInfo() {
    GetSiteInfo().catch(res =>{
      this.setData({
        siteInfo: res.data.site_info
      });
      setNavBarTitle(res.data.site_info.name || PNT.default);
    });
  },

  /**
   * 获取移动端 Banner 广告
   * @description 智能识别是否为优惠地址或商品地址，点击跳转相应小程序页面
   * @author darlang
   */
  getBanner() {
    var that = this;
    GetBannerList().then(res => {
      that.setData({
        bannerLst: res.banners
      })
    });
  },
//头条
  ttlb:function(){
  wx.navigateTo({
    url: '/pages/message/notices/index',
  })
},
  /**
   * 页面跳转
   * @author darlang
   */
  pushPath(e) {
    const items = e.currentTarget.dataset;
    if(items.type == "sign"){
      if(!this.loginModal.check()){
        return false;
      }
    }
    if (items.type == 'team' || items.type == 'activities'){
      // showToast('功能开发中...');
      return false;
    }
    const pathData = [
      {type: 'list',path: '/pages/goods/list/list?catId='+items.cat},
      {type:'team',path:'/pages/team/team'},
      { type: 'coupon', path: '/pages/coupon/coupon' },
      { type: 'qiangou', path: '/pages/seckill/seckill' },
      {type: 'score',path: '/pages/points/index/index'},
      {type: 'cashgift',path: '/pages/member/cashgift/info/info'},
      {type: 'activities',path: '/pages/message/activity/index'},
      {type: 'level',path: '/pages/member/level/level'}, 
      {type: 'notices',path: '/pages/message/notices/index'},
      {type: 'goods',path: '/pages/goods/detail/detail?id='+items.id},
      {type: 'activity',path: '/pages/message/activity/detail?id='+items.tid},
      {type: 'product',path: '/pages/goods/detail/detail?id='+items.tid},
      { type: 'article', path: '/pages/message/detail/detail?id=' + items.id },
      { type: 'actlist', path: '/pages/goods/actlist/list?type=' + items.cat },
      { type: 'sign', path: '/pages/member/qiandao/list/list' },
      // { type: 'fish', path: '/pages/member/qiandao/list/list' },
    ];
    pushPagePath(e,pathData);
  },

  detail: function (e) {
    var status = e.currentTarget.dataset.status;
    if (status) {
      wx.navigateTo({
        url: '/pages/seckill/detail?id=' + e.currentTarget.dataset.id + "&tbid=" + e.currentTarget.dataset.tbid,
      })
    } else {
      wx.navigateTo({
        url: '/pages/goods/detail/detail?id=' + e.currentTarget.dataset.id,
      })
    }
  },

  /**
   * 站内快讯
   * @author darlang
   */
  getNotices() {
    if (!shopNoticeCatId) {
      return false;
    }
    GetArticleList(1,6,shopNoticeCatId).then(res => {
      this.setData({
        noticeLst: res.banners
      });
    });
  },

  /**
   * 站内快讯
   * @author darlang
   */
  
  flashSaleBytime() {
    if(!this.data.flag){
      return;
    }
    this.data.flag = false;
      FlashSaleBytime({}).then(res => {
        if(res.error_code == 10000){
          this.setData({
            flash: res.data,
            strtotime: res.strtotime,
            flashFlag:true,
            title:res.title,
            flag:true,
          });
        }else{
          this.setData({
            flashFlag:false,
            flag: true,
          })
        }

    });
  },

  /**
   * 首页展示产品
   * @author darlang
   */
  getPorducts() {
    // GetHomeGoodsList().then(res => {
    //   console.log(res)
    //   this.setData({
    //     goodProducts: res.banners.best || '',
    //     hotProducts: res.banners.hot || '',
    //     recentlyProducts: res.banners.new || ''
    //   });
    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 页面渲染完成
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 页面显示
    var self = this;
    setTimeout(function(){
      self.countDown();
    },2000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // 页面隐藏
    clearTimeout(inter)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(inter)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getIndexPage();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    try {
      var shareName = this.data.siteInfo.name;
      var imgUrl = this.data.bannerLst[0].photo.large;
    } catch(e) {
      // console.log(e)
    }
    return {
      title: shareName || PNT.default,
      imageUrl: imgUrl || '/images/default_image.png',
      path: '/pages/index/index',
      success() {},
      fail() {},
      complete() {}
    };
  },

  onPageScroll: function () {
    // 页面滚动时执行
    var that = this;
    wx.createSelectorQuery().select('#scroll').boundingClientRect(function (rect) {
      rect.id      // 节点的ID
      rect.dataset // 节点的dataset
      rect.left    // 节点的左边界坐标
      rect.right   // 节点的右边界坐标
      rect.top     // 节点的上边界坐标
      rect.bottom  // 节点的下边界坐标
      rect.width   // 节点的宽度
      rect.height  // 节点的高度
          if(rect.top <= 0){
              that.setData({
                scroll:true,
              })
          }
      if (rect.top > 0){
            that.setData({
              scroll: false,
            })
          }
    }).exec()
  },
});
